package com.soloyogame.anitoys.center.web.controller.manage.help;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.soloyogame.anitoys.center.web.controller.BaseController;
import com.soloyogame.anitoys.center.web.util.LoginUserHolder;
import com.soloyogame.anitoys.center.web.util.RequestHolder;
import com.soloyogame.anitoys.db.bean.User;
import com.soloyogame.anitoys.db.commond.Catalog;
import com.soloyogame.anitoys.db.commond.Help;
import com.soloyogame.anitoys.db.page.PagerModel;
import com.soloyogame.anitoys.service.CatalogService;
import com.soloyogame.anitoys.service.HelpService;
import com.soloyogame.anitoys.service.IndexImgService;

import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


/**
 * 文章管理
 * @author alei
 */
@Controller
@RequestMapping("/manage/helpsmanage/")
public class HelpAction extends BaseController<Help> 
{
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(HelpAction.class);
    private static final String page_toList = "/manage/help/helpList";
    private static final String page_toEdit = "/manage/help/helpEdit";
    private static final String page_toAdd = "/manage/help/helpEdit";
    private HelpAction() {
        super.page_toList = page_toList;
        super.page_toAdd = page_toAdd;
        super.page_toEdit = page_toEdit;
    }
    @Autowired
	private HelpService helpService;
    @Autowired
	private IndexImgService indexImgService;
    @Autowired
	private CatalogService catalogService;

//	private String type;//文章类型。通知：notice；帮助：help
	
	private List<Help> help;// 门户新闻列表

    @Autowired
	public HelpService getService() {
		return helpService;
	}

	public List<Help> getHelp() {
		return help;
	}

	public void setHelp(List<Help> help) {
		this.help = help;
	}

	@Override
	public void insertAfter(Help e) {
		e.clear();
		
//		String type = e.getType();
//		e.clear();
//		e.setType(type);
	}
	
	/**
	 * 新增或者修改后文章的状态要重新设置为未审核状态
	 */
	@Override
    @RequestMapping(value = "insert", method = RequestMethod.POST)
	public String insert(HttpServletRequest request, Help e, RedirectAttributes flushAttrs) throws Exception 
	{
		logger.error("HelpAction code = " + e.getCode());
		User user = LoginUserHolder.getLoginUser();
		e.setCreateAccount(user.getUsername());
		e.setStatus(Help.news_status_n);//未审核
		getService().insert(e);
		return "redirect:toEdit2?id="+e.getId();
	}
	
	/**
	 * 修改文章
	 */
	@Override
    @RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(HttpServletRequest request, Help e, RedirectAttributes flushAttrs) throws Exception {
		logger.error("HelpAction code = ");
		logger.error("HelpAction code = " + e.getCode()+",id="+e.getId());
//		getE().setStatus(Help.news_status_n);//未审核
		
		getService().update(e);
		
//		getSession().setAttribute("insertOrUpdateMsg", "更新成功！");
//		getResponse().sendRedirect(getEditUrl(e.getId()));
		return "redirect:toEdit2?id="+e.getId();
	}
	
	//列表页面点击 编辑商品
    @RequestMapping(value = "toEdit")
	public String toEdit(Help e, ModelMap model) throws Exception {
//		getSession().setAttribute("insertOrUpdateMsg", "");
		return toEdit0(e, model);
	}
	
	/**
	 * 添加或编辑商品后程序回转编辑
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value = "toEdit2")
	public String toEdit2(Help e, ModelMap model) throws Exception {
		return toEdit0(e, model);
	}

    @RequestMapping(value = "toEdit0")
	private String toEdit0(Help e, ModelMap model) throws Exception {
        model.addAttribute("catalogsArticle",loadCatalogs2("a"));
		return super.toEdit(e, model);
	}
	
	/**
	 * 同步缓存内的新闻
	 * 审核通过，记录将会出现在门户上
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value = "updateStatusY", method = RequestMethod.POST)
	public String updateStatusY(String[] ids, String type, RedirectAttributes flushAttrs) throws Exception {
		helpService.updateStatus(ids,Help.news_status_y);
		addMessage(flushAttrs, "操作成功!");
		return "redirect:selectList";
	}
	/**
	 * 审核未通过,记录将不会出现在门户上
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "updateStatusN", method = RequestMethod.POST)
	public String updateStatusN(String[] ids, String type, RedirectAttributes flushAttrs) throws Exception {
		helpService.updateStatus(ids,Help.news_status_n);
		addMessage(flushAttrs, "操作成功!");
		return "redirect:selectList";
	}

	/**
	 * 显示指定的文章
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value = "up")
	public String up(Help e, RedirectAttributes flushAttrs) throws Exception {
		return updateDownOrUp0(e, Help.news_status_y, flushAttrs);
	}

	/**
	 * 不显示指定的文章
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value = "down")
	public String down(Help e, RedirectAttributes flushAttrs) throws Exception {
		return updateDownOrUp0(e, Help.news_status_n, flushAttrs);
	}
	
	private String updateDownOrUp0(Help e, String status, RedirectAttributes flushAttrs) throws Exception {
		if(StringUtils.isBlank(e.getId())){
			throw new NullPointerException("参数不能为空！");
		}
		
		Help help = new Help();
		help.setId(e.getId());
		help.setStatus(status);
		helpService.updateDownOrUp(help);
		addMessage(flushAttrs, "更新成功!");
		return "redirect:toEdit2?id="+e.getId();
	}
	
	/**
	 * 检查文章code的唯一性
	 * @return
	 * @throws IOException
	 */
    @RequestMapping(value = "unique")
    @ResponseBody
	public String unique(Help e) throws IOException{
		
		logger.error("检查文章code的唯一性");
		if(StringUtils.isBlank(e.getCode())){
			throw new NullPointerException("参数不能为空！");
		}
		int c = helpService.selectCount(e);
		if(StringUtils.isBlank(e.getId())){
			if(c==0){
				return "{\"ok\":\"文章code可以使用!\"}";
			}else{
				return "{\"error\":\"文章code已经被占用!\"}";
			}
		}else{
			Help help = helpService.selectById(e.getId());
			if(help.getCode().equals(e.getCode()) || c==0){
				return "{\"ok\":\"文章code可以使用!\"}";
			}else{
				return "{\"error\":\"文章code已经被占用!\"}";
			}
		}
		
//		return null;
	}

	@Override
    @RequestMapping(value = "toAdd")
	public String toAdd(Help e, ModelMap model) throws Exception {
		String type = e.getType();
		e.clear();
		e.setType(type);
        model.addAttribute("e", e);
        model.addAttribute("catalogsArticle", loadCatalogs2("a"));
		return page_toAdd;
	}
	
	@Override
	protected void selectListAfter(PagerModel pager) {
		pager.setPagerUrl("selectList");
        RequestHolder.getRequest().setAttribute("catalogsArticle", loadCatalogs2("a"));
	}
	
	/**
     * 重写批量删除
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "deletesHelp", method = RequestMethod.POST)
    public String deletesHelp(HttpServletRequest request, String[] ids,String type, @ModelAttribute("e") Help e, RedirectAttributes flushAttrs) throws Exception 
    {
        getService().deletes(ids);
        addMessage(flushAttrs, "操作成功！");
        return "redirect:selectList";
    }
    
    /**
	 * 原来递归的方式修改为非递归方式。
	 * 非递归方法查询商品/文章目录结构，并且自动排序。
	 * @param type
	 */
	private List<Catalog> loadCatalogs2(String type){
        List<Catalog> catalogs = Lists.newLinkedList();
		Catalog cc = new Catalog();
		cc.setType(type);
		List<Catalog> catalogsList = catalogService.selectList(cc);
		if(catalogsList!=null){

			Map<String, Catalog> map = new HashMap<String, Catalog>();
			for(Iterator<Catalog> it = catalogsList.iterator();it.hasNext();){
				Catalog item = it.next();

				if(StringUtils.isNotBlank(item.getPid()) && item.getPid().equals("0")){
					//是否在导航栏显示中文化
					if(item.getShowInNav().equals(Catalog.catalog_showInNav_y)){
						item.setShowInNavStr("是");
					}

					map.put(item.getId(), item);
					it.remove();
				}
			}

			for(Iterator<Catalog> it = catalogsList.iterator();it.hasNext();){
				Catalog item = it.next();
				if(StringUtils.isNotBlank(item.getPid())){
//							list.add(item);
					Catalog rootItem = map.get(item.getPid());
					if(rootItem!=null){
						if(rootItem.getChildren()==null){
							rootItem.setChildren(new LinkedList<Catalog>());
						}
						rootItem.getChildren().add(item);
					}
					it.remove();
				}
			}

			for(Iterator<Entry<String, Catalog>> it = map.entrySet().iterator();it.hasNext();){
				catalogs.add(it.next().getValue());
			}

			//对主类别和子类别进行排序
			Collections.sort(catalogs, new Comparator<Catalog>() {
				public int compare(Catalog o1, Catalog o2) {
					if (o1.getOrder1() > o2.getOrder1()) {
						return 1;
					} else if (o1.getOrder1() < o2.getOrder1()) {
						return -1;
					}
					return 0;
				}
			});

			for(int i=0;i<catalogs.size();i++){
				if(catalogs.get(i).getChildren()==null){
					continue;
				}
				Collections.sort(catalogs.get(i).getChildren(), new Comparator<Catalog>() {
					public int compare(Catalog o1, Catalog o2) {
						if (o1.getOrder1() > o2.getOrder1()) {
							return 1;
						} else if (o1.getOrder1() < o2.getOrder1()) {
							return -1;
						}
						return 0;
					}
				});
			}
		}
        return catalogs;
	}
}
